package com.sch.wanandroid.ui.main.home

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.ArticleAdapter
import com.sch.wanandroid.adapter.HomeBannerAdapter
import com.sch.wanandroid.base.BaseFragment
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.databinding.FragmentRefreshListBinding
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.entity.BannerBean
import com.sch.wanandroid.ui.web.WebActivity
import com.sch.wanandroid.util.AppManager
import com.youth.banner.Banner
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_refresh_list.*

/**
 * 主页
 */

class HomeFragment : BaseFragment() {
    companion object {
        fun getInstance(): HomeFragment = HomeFragment()
    }

    private lateinit var homeViewModel: HomeViewModel
    private lateinit var dataBinding: FragmentRefreshListBinding

    //文章适配器
    private val articleAdapter by lazy { ArticleAdapter() }

    //文章列表数据
    private val articleList by lazy { mutableListOf<ArticleBean>() }

    //获取文章数据时的页码，从0开始
    private var pageNum = 0

    //收藏或取消收藏是点击的位置
    private var collectPosition = 0

    /**
     * 点击收藏后将点击事件上锁,等接口有相应结果再解锁
     * 避免重复点击产生的bug  false表示没锁，true表示锁住
     */
    private var lockCollectClick = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        dataBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_refresh_list, container, false)
        dataBinding.lifecycleOwner = this
        return dataBinding.root
    }


    override fun init(savedInstanceState: Bundle?) {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = articleAdapter
        //取消滑动越界效果
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
        val mBannerView = layoutInflater.inflate(R.layout.layout_banner, null)
        articleAdapter.addHeaderView(mBannerView)
        val banner = mBannerView.findViewById<Banner<BannerBean, HomeBannerAdapter>>(R.id.banner)

        //加载中动画
        loadingTip.loading()
        loadData()
        initListener()
        homeViewModel.bannerLiveData.observe(this, Observer {
            banner.setAdapter(HomeBannerAdapter(it))
                .addBannerLifecycleObserver(this)
                .indicator = CircleIndicator(context)
        })
        homeViewModel.topArticleLiveData.observe(this, Observer {
            articleList.addAll(0, it)
            articleAdapter.setList(articleList)
        })
        homeViewModel.articleLiveData.observe(this, Observer {
            setData(it)
        })
        homeViewModel.errorMsg.observe(this, Observer {
            onError(it)
        })
        homeViewModel.collectSuccess.observe(this) {
            if (it) {
                collectSuccess()
            }
        }
        homeViewModel.uncollectSuccess.observe(this) {
            if (it) {
                unCollectSuccess()
            }
        }
    }

    /**
     * 加载数据
     * 初始化，网络出错重新加载，刷新均可使用
     */
    private fun loadData() {
        //banner只加载一次
        if (homeViewModel.bannerLiveData.value == null || homeViewModel.bannerLiveData.value!!.isEmpty()) {
            homeViewModel.getBanner()
        }
        articleList.clear()
        articleAdapter.setList(articleList)
        homeViewModel.getTopArticleData()
        pageNum = 0
        homeViewModel.getArticleData(pageNum)
    }

    private fun initListener() {
        dataBinding.loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                loadingTip.loading()
                loadData()
            }
        })
        dataBinding.smartRefresh.setOnRefreshListener {
            Log.e("test", "Refresh")
            loadData()
        }
        dataBinding.smartRefresh.setOnLoadMoreListener {
            Log.e("test", "LoadMore")
            pageNum++
            homeViewModel.getArticleData(pageNum)
        }
        articleAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, articleList[position].link)
                putString(Constants.WEB_TITLE, articleList[position].title)
            }, WebActivity::class.java, false)
        }
        articleAdapter.addChildClickViewIds(R.id.ivCollect)
        articleAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivCollect) {
                if (!AppManager.isLogin()) {
                    SmartToast.show("请先登录")
                    return@setOnItemChildClickListener
                }
                if (position < articleList.size && !lockCollectClick) {
                    lockCollectClick = true
                    collectPosition = position
                    articleList[position].apply {
                        if (collect) {
                            homeViewModel.unCollect(id)
                        } else {
                            homeViewModel.collect(id)
                        }
                    }
                }
            }
        }

    }

    private fun setData(list: List<ArticleBean>) {
        dismissRefresh()
        //如果list不是空，刷新列表
        if (list.isNotEmpty()) {
            articleList.addAll(list)
            articleAdapter.setList(articleList)
        } else {
            //如果当前页面没有数据，展示无数据
            if (articleList.size == 0) loadingTip.showEmpty()
            //如果当前页面有数据，则没有更多数据
            else SmartToast.info("没有更多数据了")
        }
    }

    fun onError(msg: String?) {
        //释放收藏锁
        lockCollectClick = false
        //请求失败将page -1
        if (pageNum > 0) pageNum--
        dismissRefresh()
        //如果当前没有数据，展示网络异常
        if (articleList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(msg)
    }

    /**
     * 收藏成功
     */
    private fun collectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = true
            articleAdapter.setData(collectPosition, articleList[collectPosition])
        }
    }

    /**
     * 取消收藏成功
     */
    private fun unCollectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = false
            articleAdapter.setData(collectPosition, articleList[collectPosition])
        }
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }

    fun scrollToTop() {
        recyclerView.run {
            smoothScrollToPosition(0)
        }
    }
}